package com.tanhua.api.mongo;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.mongo.*;
import com.tanhua.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class PublishApiImpl implements PublishApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    public String savePublish(Publish publish) {
        // 1 保存数据到动态发布表中
        publish.setCreated(System.currentTimeMillis());
        //给大数据使用的 人家的要求是：该字段是数值类型的唯一值
        Long pid = idService.getNextId("quanzi_publish");
        publish.setPid(pid); //pid:数值类型的自增标识（唯一值）
        publish.setId(new ObjectId()); //自己去设置mongodb的id   1234567
        mongoTemplate.insert(publish);
        // 2 记录id到个人动态表中
        Album album = new Album();
        album.setPublishId(publish.getId());
        album.setCreated(publish.getCreated());
        mongoTemplate.insert(album,"quanzi_album_"+publish.getUserId());
        // 3 查询自己的好友id
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friendsList = mongoTemplate.find(query, Friend.class);
        //4 根据好友id将动态发布id放图好友的时间线表中
        if(CollectionUtil.isNotEmpty(friendsList)){
            for (Friend friend : friendsList) {
                Long friendId = friend.getFriendId();
                //插入到好友的时间线中
                TimeLine timeLine = new TimeLine();
                timeLine.setUserId(publish.getUserId());
                timeLine.setPublishId(publish.getId());
                timeLine.setCreated(publish.getCreated());
                mongoTemplate.insert(timeLine,"quanzi_time_line_"+friendId);
            }
        }

        return publish.getId().toString();
    }

    @Override
    public PageBeanVo findPublishAll(Integer page, Integer pagesize, Long userId) {

        // 1 带着自己的id查询个人动态表 获取到所有的动态id
        Query query = new Query();
        query.skip( (page-1)*pagesize ).limit(pagesize); //分页
        query.with(new Sort(Sort.Direction.DESC,"created")); //倒序
        List<Album> albumsList = mongoTemplate.find(query, Album.class,"quanzi_album_"+userId);
        //2 在根据所有的动态id获取到当前用户的所有发布的动态信息
        ArrayList<Publish> publishList=null;
        if(CollectionUtil.isNotEmpty(albumsList)){
            publishList = new ArrayList<>();
            for (Album album : albumsList) {
                    //获取每个发布的动态
                Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
                //判断只要动态是审核通过的  0:未审核   1：已审核
                if(publish.getState()==1){
                    publishList.add(publish); //2个(本身4个)
                }

            }
        }
        String size=publishList.size()+"";
        PageBeanVo pageBeanVo = new PageBeanVo(page, pagesize, Long.parseLong(size), publishList);

        return pageBeanVo;
    }

    @Override
    public PageBeanVo findFriendPublish(Integer page, Integer pagesize, Long userId) {

        // 分页查询自己的时间线表 按照创建时间做排序
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip( (page-1)*pagesize ).limit(pagesize);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        List<Publish> publishList=new ArrayList<Publish>();
        if(CollectionUtil.isNotEmpty(timeLineList)){
            for (TimeLine timeLine : timeLineList) {
                Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);
                if(publish.getState()==1){
                    publishList.add(publish);
                }
            }
        }

        Long size = new Long(publishList.size());
        return new PageBeanVo(page,pagesize,size,publishList);
    }

    @Override
    public PageBeanVo findRecommendPublish(Integer page, Integer pagesize, Long userId) {
        // 分页查询自己的时间线表 按照创建时间做排序
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip( (page-1)*pagesize ).limit(pagesize);
        List<RecommendQuanzi> recommendQuanziList = mongoTemplate.find(query, RecommendQuanzi.class);

        List<Publish> publishList=new ArrayList<Publish>();
        if(CollectionUtil.isNotEmpty(recommendQuanziList)){
            for (RecommendQuanzi recommendQuanzi : recommendQuanziList) {
                Publish publish = mongoTemplate.findById(recommendQuanzi.getPublishId(), Publish.class);
                if(publish.getState()==1){
                    publishList.add(publish);
                }
            }
        }

        Long size = new Long(publishList.size());
        return new PageBeanVo(page,pagesize,size,publishList);
    }

    @Override
    public Publish findById(String publishId) {
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }

    @Override
    public PageBeanVo findMessages(Integer page, Integer pagesize, Long userId, Integer state) {

        Query query = new Query();
        Criteria criteria = new Criteria();
        if(userId!=null){
            criteria.and("userId").is(userId);
        }
        if(state!=null){
            criteria.and("state").is(state);
        }
        query.addCriteria(criteria);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        Long count = mongoTemplate.count(query, Publish.class);

        return new PageBeanVo(page,pagesize,count,publishList);
    }

    @Override
    public void updateState(String publishId, int state) {

        Query query = new Query(Criteria.where("id").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.upsert(query,update,Publish.class);
    }

    @Override
    public Publish findByPid(String pid) {
        long id = Long.parseLong(pid);
        Query query = new Query(Criteria.where("pid").is(id));
        Publish publish = mongoTemplate.findOne(query, Publish.class);
        return publish;
    }
}
